package com.gking.centerSystem.serviceUtils.QWen;

import com.gking.centerSystem.common.BaseContext;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.entity.AiServiceRecord;
import com.gking.centerSystem.entity.pojo.aiChat.ChatMessage;
import com.gking.centerSystem.entity.pojo.aiChat.ChatRequest;
import com.gking.centerSystem.entity.pojo.aiChat.ChatResponse;
import com.gking.centerSystem.service.AiServiceRecord.AiServiceRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;

@Slf4j
@Service
public class QWenServiceImpl implements QWenService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private AiServiceRecordService aiServiceRecordService;

    @Value("${qwen.api.key}")
    private String QWenKey;

    @Value("${qwen.api.url}")
    private String QWenUrl;

    @Value("${qwen.api.model}")
    private String QWenModel;


    /**
     * 添加AI服务记录
     *
     * @param message         向AI提问的消息
     * @param description     对于此次提问的日志描述
     * @param status          AI服务响应状态
     * @param responseContent AI服务响应内容
     * @param consumeTime     此次服务消耗时间
     */
    @Async("aiServiceRecordTaskExecutor")
    public void addServiceRecord(String message, String description, Integer status,
                                 String responseContent, long consumeTime) {
        AiServiceRecord aiServiceRecord = new AiServiceRecord();
        aiServiceRecord.setUserMessage(message);
        aiServiceRecord.setDescription(description);
        aiServiceRecord.setAccessUserId(BaseContext.getCurrentId());
        aiServiceRecord.setResponseStatus(status);
        aiServiceRecord.setResponseContent(responseContent);
        aiServiceRecord.setConsumeTime(consumeTime);
        aiServiceRecordService.addRecord(aiServiceRecord);
    }


    @Override
    public String oneTimeSimpleQA(String userMessage) {
        try {
            // 构建请求
            ChatRequest request = new ChatRequest();
            request.setModel(QWenModel);
            request.setMessages(Arrays.asList(
                    new ChatMessage("user", userMessage)
            ));

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + QWenKey);

            HttpEntity<ChatRequest> entity = new HttpEntity<>(request, headers);

            // 发送请求
            ResponseEntity<ChatResponse> response = restTemplate.exchange(
                    QWenUrl,
                    HttpMethod.POST,
                    entity,
                    ChatResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                String content = response.getBody().getChoices().get(0).getMessage().getContent();

                log.info("AI服务调用成功: {} ", content);
                return content;
            } else {
                return null;
            }

        } catch (Exception e) {
            log.error("AI服务调用失败: {}", e.getMessage());
            throw new ProgramException("AI服务调用失败: " + e.getMessage());
        }
    }

}
